package com.javaDemo.ti;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Stack;

/**
 * @ClassName: Xiayigegendayuansu
 * @Auther: csy
 * @Date: 2022/7/7 19:38
 * @Description:
 */
public class Xiayigegendayuansu {
    public static void main(String[] args) {
        int[] a={4,1,2};
        int[] b={1,3,4,2};
        System.out.println(nextGreaterElement(a,b));
    }
    public static int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Stack<Integer> temp = new Stack<>();
        int[] res = new int[nums1.length];
        Arrays.fill(res,-1);
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0 ; i< nums1.length ; i++){
            hashMap.put(nums1[i],i);
        }
        temp.add(0);
        for (int i = 1; i < nums2.length; i++) {
            if (nums2[i] <= nums2[temp.peek()]) {
                temp.add(i);
            } else {
                while (!temp.isEmpty() && nums2[temp.peek()] < nums2[i]) {
                    if (hashMap.containsKey(nums2[temp.peek()])){
                        Integer index = hashMap.get(nums2[temp.peek()]);
                        res[index] = nums2[i];
                    }
                    temp.pop();
                }
                temp.add(i);
            }
        }

        return res;
    }
}
